package com.demo.travel.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.demo.travel.R;
import com.demo.travel.utils.SharedPreferencesUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment {

    private Unbinder unbinder;

    public Context mContext;

    public boolean isWhiteBtn;

    private static Toast toast;

    public abstract int getLayout();

    public abstract String getTitle();

    public void initData(){};

    public abstract void requestData();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext=getActivity();
        View view = inflater.inflate(getLayout(), container, false);
        TextView title=view.findViewById(R.id.title_tv);
        if (title != null) {
            title.setText(getTitle());
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);
        initData();
        requestData();
    }

    /**
     * 显示提示  toast
     *
     * @param msg 提示信息
     */
    @SuppressLint("ShowToast")
    public void showToast(String msg) {
        try {
            if (null == toast) {
                toast = Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT);
            } else {
                toast.setText(msg);
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    toast.show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            //解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }

    public void putString(String key, String value){
        SharedPreferencesUtils.getInstance(getActivity()).putString(key, value);
    }

    public String getString(String key){
        return SharedPreferencesUtils.getInstance(getActivity()).getString(key);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    public String getStringText(int id){
        return getResources().getString(id);
    }

}
